<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/16
 * Time: 19:56
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\system;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\AccountPlatform;
use app\common\model\SysCountries;
use app\common\service\platform\BasePlatformService;
use app\common\service\system\AccountService;
use think\facade\Validate;

class AccountController extends BaseController
{
    /**
     * 首页
     * @return string
     * @date 2020/09/17
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $where = [];
            $order = "sort desc, platform_id,username";
            $limit = $this->getPageSize();
            $model = Account::with(['platform'])
                ->order($order);
            // 解析查询条件
            $this->searchModel($model, [
                'eq' => ['platform_id'],
                'times' => ['date' => 'create_time']
            ]);
            if($name = $this->request->request("name"))
                $model->whereRaw("username like :a or store_name like :b", ["a"=>"%$name%", "b"=>"%$name%"]);
            // 执行分页查询
            $ret = $model->where($where)->paginate($limit);
            $this->assign("list", $ret->getCollection());
            $this->assign("page", $ret->render());
            return $this->fetch('lists');
        }
        $this->assign("country", SysCountries::getCodeNameCh());
        $this->assign("platform", AccountPlatform::getAll());
        return $this->fetch('index');
    }

    /**
     * 保存数据
     * @date 2020/09/17
     * @author longli
     */
    public function save()
    {
        if(!$this->request->isPost()) $this->error('非法操作');
        $post = $this->request->post();
        // 普通验证
        $validate = Validate::make([
            'platform_id'  => 'require',
            'username'  => 'require|max:128',
            'send_day'  => 'egt:0',
            'store_name'  => 'require|max:128',

        ],[
            'platform_id.require' => '平台必须选择',
            'username.require' => '账号必填',
            'username.max' => '账号过长',
            'send_day.egt' => '发货天数不能小于0',
            'store_name.require' => '店铺名必填',
            'store_name.max' => '店铺名过长',
        ]);
        if(!$validate->batch()->check($post))$this->error(join(', ', $validate->getError()));

        // 如果是更新则要再验证 token
        if(isset($post['account_id']))
        {
            if(($token = $this->validateToken($post)) && !is_array($token)) $this->error($token);
            $post['token'] = $token;
        }
        AccountService::getInstance()->addAccount($post)
            ? $this->success('保存成功')
            : $this->error('保存失败');
    }

    /**
     * 状态
     * @date 2020/09/17
     * @author longli
     */
    public function lock()
    {
        $accountId = $this->request->get("account_id");
        if(empty($accountId)) $this->error('非法操作');
        $active = $this->request->get("lock");
        Account::get($accountId)->save(["is_active" => $active]);
        $this->success('操作成功');
    }

    /**
     * 删除账号
     * @date 2020/09/17
     * @author longli
     */
    public function delete()
    {
        $accountId = $this->request->get("account_id");
        if(empty($accountId)) $this->error('非法操作');
        Account::destroy($accountId)
            ? $this->success('删除成功')
            : $this->error('删除失败');
    }

    /**
     * 编辑
     * @return string
     * @date 2020/09/17
     * @author longli
     */
    public function add()
    {
        $accountId = $this->request->get("account_id");

        if(!empty($accountId))
        {
            $account = Account::with(['platform'])->get($accountId);
            $this->assign("account", $account);
            if(($classes = BasePlatformService::getClasses($account->platform->classes)) && BasePlatformService::classesExist($classes))
            {
                $this->assign("tokenField", $classes::$tokenField);
            }
        }
        else
        {
            $this->assign("platform", AccountPlatform::getAll());
        }
        return $this->fetch("add");
    }

    /**
     * 验证账号录入的 token 信息
     * @param array $post 表单提交过来的数据
     * @return string|array
     * @date 2020/09/17
     * @author longli
     */
    private function validateToken($post = [])
    {
        $account = Account::get($post['account_id']);
        if(!$account) return "账号不存在";
        $classes = BasePlatformService::getClasses($account->platform->classes);
        if(!BasePlatformService::classesExist($classes)) return "对接类不存在";
        $token = [];
        foreach($post as $k => $v)
        {
            if(Tools::startWith($k, 'token_') && !empty($v)) $token[substr($k, 6)] = $v;
        }

        $tokenField = $classes::$tokenField;
        $flag = false;
        foreach($tokenField['required'] as $r)
        {
            if(!empty($token[$r['field']]))
            {
                $flag = true;
                break;
            }
        }
        if($flag)
        {
            foreach($tokenField['required'] as $r)
            {
                if(empty($token[$r['field']])) return "【{$r['field']}】不能为空";
            }
        }
        return $token;
    }
}